<template>
    <div :class="['dagre-base_wrapper', {'is-screen-full': isFullscreen }]" id="mapviewwrap">
        <ul class="dagre-header-wrap">
            <li class="action-item" @click="exportPng">
                <Tooltip content="下载思维导图" placement="bottom">
                    <i class="icon iconxiazai"></i>
                </Tooltip>
            </li>
            <li class="action-item" @click="previewScreenFull">
                <Tooltip :content="isFullscreen ?'关闭全屏':'全屏查看'" placement="bottom">
                    <i :class="`icon ${isFullscreen ? 'iconguanbiquanping':'iconquanping'}`"></i>
                </Tooltip>
            </li>
            <li 
                class="action-item" 
                v-for="(item, index) in redirects" 
                :key="index"  
                @click="onSelectDir(item, index)">
                <Tooltip :content="item.name" placement="bottom">
                    <i v-if="item.value ==='RL'" style="transform: rotate(-90deg);display: block;" class="icon icona-cengjijiagoubuju"></i>
                    <i v-else-if="item.value ==='LR'" style="transform: rotate(90deg);display: block;" class="icon icona-cengjijiagoubuju"></i>
                    <i v-else-if="item.value ==='TB'" style="transform: rotate(-180deg);display: block;" class="icon icona-cengjijiagoubuju"></i>
                    <i v-else class="icon icona-cengjijiagoubuju"></i>
                </Tooltip>
            </li>
        </ul>
        <div class="custom-map-mind-wrap" id="mapcontainernew"></div>
        <!-- <img style="position: absolute;top: 0px;"> -->
    </div>
</template>

<script setup>
import { Canvg, presets } from "canvg";
import screenfull from 'screenfull';
import { DagreMap } from "./toolkit";
import { toolbar } from './toolbar';

const dirIndex = ref(0);
const currentIndex = ref(-1)
const customPaper = ref(null);
const isFullscreen = ref(false)
const preset = presets.offscreen();

// 布局方向
const redirects = ref([
    { name: "右左布局", value: "LR" },
    { name: "左右布局", value: "RL" },
    { name: "上下布局", value: "BT" },
    { name: "下上布局", value: "TB" },
]);

// 想让节点对齐，需要设置宽度
const nodeList = ref([
    { id: "kspacey", node: { label: "Kevin Spacey", width: 144, height: 50 } },
    { id: "kspacey2", node: { label: "Kevin Spacey 2", width: 144, height: 50 } },
    { id: "swilliams", node: { label: "Saul Williams", width: 160, height: 50 } },
    { id: "bpitt", node: { label: "Brad Pitt", width: 144, height: 50 } },
    { id: "css", node: { label: "CSS 3", width: 144, height: 50 } },
    { id: "html", node: { label: "HTML 5", width: 144, height: 50 } },
    { id: "js", node: { label: "JavaScript 2024", width: 144, height: 50 } },
    { id: "hford", node: { label: "Harrison Ford", width: 168, height: 50 } },
    { id: "lwilson", node: { label: "Luke Wilson", width: 144, height: 50 } },
    { id: "kbacon", node: { label: "Kevin Bacon", width: 121, height: 50 } },
]);
const edgeList = ref([
    { sourceId: "kspacey", targetId: "swilliams" },
    { sourceId: "kspacey2", targetId: "swilliams" },
    { sourceId: "swilliams", targetId: "kbacon" },
    { sourceId: "bpitt", targetId: "kbacon" },
    { sourceId: "css", targetId: "bpitt" },
    { sourceId: "html", targetId: "bpitt" },
    { sourceId: "js", targetId: "bpitt" },
    { sourceId: "hford", targetId: "lwilson" },
    { sourceId: "lwilson", targetId: "kbacon" },
]);

// 切换方向
function onSelectDir(item, index) {
    dirIndex.value = index;
    customPaper.value.update(redirects.value[dirIndex.value].value);
}

// 全屏查看
function previewScreenFull () {
    const container = document.querySelector('#mapviewwrap')
    if (screenfull.isEnabled) {
        screenfull.on('change', () => {
            isFullscreen.value = screenfull.isFullscreen
			// console.log('Am I fullscreen?', screenfull.isFullscreen ? 'Yes' : 'No');
		});
        if (!screenfull.isFullscreen) {
            screenfull.request(container, { navigationUI: 'show' }).then(res => {
                renderMap()
            })
        }
    }
    if (screenfull.isFullscreen) {
        screenfull.exit().then(res => {
            renderMap()
        })
    }
}

function exportPng () {
    customPaper.value.exportPng()
    // const container = document.querySelector('#mapcontainernew')
    // const svgDom = container.querySelector('svg')
    // const img = document.querySelector('img')
    // svgDom.removeAttributeNS(null, 'xmlns:xlink')
    // svgDom.removeAttributeNS(null, 'xmlns:ev')
    // const { width:svgWidth, height:svgHeight } = svgDom.getBoundingClientRect()
    // // 将svg转换成图片可以预览
    // toPng({
    //     width: svgWidth,
    //     height: svgHeight,
    //     svg: svgDom.outerHTML
    // }).then(pngUrl => {
    //     // img.src = pngUrl
    // })
}

async function toPng(data) {
    const { width, height, svg } = data;
    const canvas = new OffscreenCanvas(width, height);
    const ctx = canvas.getContext("2d");
    const v = await Canvg.from(ctx, svg, preset);

    // Render only first frame, ignoring animations and mouse.
    await v.render();

    const blob = await canvas.convertToBlob();
    const pngUrl = URL.createObjectURL(blob);
    const a = document.createElement('a')
    a.style.display = 'none'
    document.body.append(a)
    a.href = pngUrl
    a.download = 'test.png'
    a.click()
    window.URL.revokeObjectURL(a.href)
    document.body.removeChild(a)
    return pngUrl;
}

function renderMap(params) {
    customPaper.value && customPaper.value.destroy()
    customPaper.value = new DagreMap("#mapcontainernew", {
        rankdir: redirects.value[dirIndex.value].value,
        nodes: nodeList.value,
        links: edgeList.value,
    });
}
nextTick(() => {
    renderMap()
});

onBeforeUnmount(() => {
    customPaper.value && customPaper.value.destroy()
})
</script>
<style lang="scss" src="./style.scss" scoped></style>
